package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportServices;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.info.ProjectInfoProperties;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServicesImpl implements ReportServices {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 获得营业额统计
     *
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);

        while (!begin.equals(end)) {//日期计算，后一天
            begin = begin.plusDays(1);
            datelist.add(begin);
        }

        List<Double> turnoverlist = new ArrayList<>();
        for (LocalDate localDate : datelist) {
            //获得这一天的凌晨
            LocalDateTime begin1 = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime end1 = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", begin1);
            map.put("end", end1);
            map.put("status", Orders.COMPLETED);
            //查询date中对应的营业额数据,这一天已经完成的订单
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;//三元运算服判断是否为空
            turnoverlist.add(turnover);

        }
        //日期以逗号隔开
        return TurnoverReportVO.
                builder().
                dateList(StringUtils.join(datelist, ","))
                .turnoverList(StringUtils.join(turnoverlist, ",")).
                build();

    }

    /**
     * 用户人数统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);

        while (!begin.equals(end)) {//日期计算，后一天
            begin = begin.plusDays(1);
            datelist.add(begin);
        }
        List<Integer> newUserlist = new ArrayList<>();//新增用户数量
        List<Integer> totalUserlist = new ArrayList<>();//总用户数量
        for (LocalDate date : datelist) {
            LocalDateTime begin1 = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime end1 = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", end1);
            Integer totalUser = userMapper.countByMap(map);//总用户数量
            map.put("begin", begin1);
            Integer newUser = userMapper.countByMap(map);//新增用户数量
            totalUserlist.add(totalUser);
            newUserlist.add(newUser);
        }


        return UserReportVO.builder()
                .dateList(StringUtils.join(datelist, ","))
                .totalUserList(StringUtils.join(totalUserlist, ","))
                .newUserList(StringUtils.join(newUserlist, ","))
                .build();
    }

    @Override//获得订单数据
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);

        while (!begin.equals(end)) {//日期计算，后一天
            begin = begin.plusDays(1);
            datelist.add(begin);
        }
        List<Integer> vaildOrderCountlist = new ArrayList<>();//每天订单有效数
        List<Integer> orderCountlist = new ArrayList<>();//每天订单总数量
        for (LocalDate date : datelist) {
            LocalDateTime begin1 = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime end1 = LocalDateTime.of(date, LocalTime.MAX);
            //订单总数
            Integer orderCount = getOrderCount(begin1, end1, null);
            //有效订单数
            Integer vaildOrderCount = getOrderCount(begin1, end1, Orders.COMPLETED);
            orderCountlist.add(orderCount);
            vaildOrderCountlist.add(vaildOrderCount);

        }

        //时间区间内订单总数量
        Integer totalCount = orderCountlist.stream().reduce(Integer::sum).get();
        /*Integer count=0;
        for (Integer i : orderCountlist) {
            count+=i;
        }*/
        //时间区间内订单总数量
        Integer vaildCount = vaildOrderCountlist.stream().reduce(Integer::sum).get();

        /*Integer countAvild=0;
        for (Integer i : vaildOrderCountlist) {
            countAvild+=i;
        }*/

        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalCount != 0)
            orderCompletionRate = vaildCount.doubleValue() / totalCount.doubleValue();

        return OrderReportVO.builder()
                .dateList(StringUtils.join(datelist, ","))
                .orderCountList(StringUtils.join(orderCountlist, ","))
                .validOrderCountList(StringUtils.join(vaildOrderCountlist, ","))
                .totalOrderCount(totalCount)
                .validOrderCount(vaildCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排名统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime begin1 = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime end1 = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> sslesTop = orderMapper.getSalesTop10(begin1, end1);
        //获得名字字符串
        List<String> name = sslesTop.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String namestring = StringUtils.join(name, ",");
        //获得名字字符串
        List<Integer> number = sslesTop.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String stringNumber = StringUtils.join(number, ",");


        return SalesTop10ReportVO
                .builder()
                .nameList(namestring)
                .numberList(stringNumber)
                .build();
    }

    @Override//导出运营数据报表
    public void exportBusinessDate(HttpServletResponse response) {
        //查询数据库，获得数据
        //前一个查询今天的前三十天数据，后一个获得昨天的日期
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN)
                , LocalDateTime.of(dateEnd, LocalTime.MAX));

        //通过poi将数据写到excel文件中
        InputStream in = this.getClass().getClassLoader().
                getResourceAsStream("template/运营数据报表模板.xlsx");
        //基于模版创建新的报表
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //填充数据
            XSSFSheet sheet = excel.getSheet("Sheet1");//获得标签页
            sheet.getRow(1).getCell(1).setCellValue("时间："
            +dateBegin+"至"+dateEnd);//填充时间
            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));
                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //抽一个方法用于查询订单数据
    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map);

    }
}
